import logging

import pymysql
from database.database_conf import DatabaseConf
from database.database_object import DatabaseObject


class MysqlObject(DatabaseObject):
    def connect(self, db_conf: DatabaseConf) -> bool:
        ret = True
        try:
            self.db_url = f"Mysql[{db_conf.db_address}:{db_conf.db_port}/{db_conf.db_name}][{db_conf.db_username}][{db_conf.db_password}]"
            logging.info(self.db_url)

            self.db_con = pymysql.connect(host=db_conf.db_address,
                                          port=int(db_conf.db_port),
                                          user=db_conf.db_username,
                                          password=db_conf.db_password,
                                          database=db_conf.db_name)
        except Exception as ex:
            ret = False
            self.last_error = str(ex)
            logging.error(ex)
        return ret

    def get_version(self) -> str:
        sql = "SELECT VERSION() AS DB_VERSION FROM DUAL"
        row = self.fetchone(sql)
        if row:
            return row[0]
        return ""

    def get_schema_list(self) -> list:
        schema_list = []
        sql = "SHOW DATABASES"
        rows = self.fetchall(sql)
        for row in rows:
            schema_list.append(row[0])
        return schema_list

    def get_table_list(self, schema_name: str) -> list:
        table_list = []
        sql = "SHOW FULL TABLES FROM `%s` WHERE Table_type != 'VIEW'" % schema_name
        rows = self.fetchall(sql)
        for row in rows:
            table_list.append(row[0])
        return table_list

    def get_filed_list(self, schema_name: str, table_name: str) -> list:
        filed_list = []
        sql = "SELECT COLUMN_NAME as field_name,column_type as field_type ,column_comment as field_desc FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s ORDER BY ORDINAL_POSITION"
        rows = self.fetchall_dict(sql, params=[schema_name, table_name])
        for row in rows:
            filed_row = dict()
            filed_row["field_name"] = row["field_name"].lower()
            filed_row["field_type"] = row["field_type"]
            filed_row["field_length"] = ""
            filed_row["field_desc"] = row["field_desc"]
            filed_list.append(filed_row)
        return filed_list
